package com.dididoctor.patient.Activity.mvp;

import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.dididoctor.patient.Activity.Capture.CaptureActivity;
import com.dididoctor.patient.Activity.ConstantValue;
import com.dididoctor.patient.Activity.Consult.ConsultActivity;
import com.dididoctor.patient.Activity.Doctor.ForumTabFragActivity;
import com.dididoctor.patient.Activity.Doctor.SearchDoctor.SearchDoctorActivity;
import com.dididoctor.patient.Activity.Message.MessageActivity;
import com.dididoctor.patient.Activity.Service.ServiceActivity;
import com.dididoctor.patient.Activity.Usercentre.UserCentreActivity;
import com.dididoctor.patient.Bean.Token;
import com.dididoctor.patient.R;
import com.dididoctor.patient.Utils.SharedPreferencesUtils;
import com.dididoctor.patient.WYY.DemoCache;
import com.netease.nim.uikit.common.ui.dialog.DialogMaker;
import com.netease.nimlib.sdk.AbortableFuture;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;


/**
 * @version 2.0
 * @类描述： 首页MVP
 * @项目名称：douDouTech
 * @类名称： SplashActivity
 * @包名称： com.doudoukeji.service.Activity.mvp
 * @创建人：张强 boy
 * @创建时间：2016/3/7 16:40
 * @修改人：
 * @修改时间：2016/3/7 16:40
 * @修改备注： new parent class(用一句话描述修改了什么)
 */
public class MainActivity extends TabActivity implements View.OnClickListener {

    private TabHost tabHost;
    //取消状态下的图片
    private final int[] normal = new int[]{R.drawable.logo_consult_nomal, R.drawable.logo_doctor_nomal, R.drawable.logo_serve_nomal, R.drawable.logo_user_nomal};
    //点击状态下的图片
    private final int[] press = new int[]{R.drawable.logo_consult_press, R.drawable.logo_doctor_press, R.drawable.logo_serve_press, R.drawable.logo_user_press};
    private final String[] names = new String[]{"咨询", "医生", "服务", "个人中心"};

    //底部图片和文本集合
    private ImageView[] images;
    private TextView[] textViews;

    //标题
    private TextView mTvTitle;
    private ImageView mImgSearch, mImgScan;

    //返回按钮
    private ImageView mBtnBack;
    private MyBroadcastReceiver mMyBroadcastReceiver;
    private MyReceiver myReceiver;

    private AbortableFuture<LoginInfo> loginRequest;
    private static final String TAG = MainActivity.class.getSimpleName();

    //活动页
//    private RelativeLayout mRelActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除titilebar使用的
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.activity_main);

        //初始化控件
        init();
    }

    /**
     * 初始化控件
     */
    private void init() {
        /***********标题栏************/
        initTopBar();

        /***********底边栏************/
        initBottomBar();

        /***********广播*****************/
        initBroadcast();
        /***********跳转广播*****************/
        initmyBroadcast();

        try {
            this.tabHost = getTabHost();
            this.tabHost.addTab(this.tabHost.newTabSpec("tab_1").setContent(new Intent(this, ConsultActivity.class)).setIndicator("TAB1"));
            this.tabHost.addTab(this.tabHost.newTabSpec("tab_2").setContent(new Intent(this, ForumTabFragActivity.class)).setIndicator("TAB2"));
            this.tabHost.addTab(this.tabHost.newTabSpec("tab_3").setContent(new Intent(this, ServiceActivity.class)).setIndicator("TAB3"));
            this.tabHost.addTab(this.tabHost.newTabSpec("tab_4").setContent(new Intent(this, UserCentreActivity.class)).setIndicator("TAB4"));
            this.tabHost.setCurrentTab(0);
        } catch (Exception ex) {
            ex.printStackTrace();
            Log.e("EXCEPTION", ex.getMessage());
        }

        //云通讯登录
        login();
    }

    /**
     * 初始化广播
     */
    private void initBroadcast() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ConstantValue.Main_CHANGE);
        mMyBroadcastReceiver = new MyBroadcastReceiver();
        //消息红点
        registerReceiver(mMyBroadcastReceiver, intentFilter);
    }

    private void initmyBroadcast() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("MyReceiver");
        myReceiver = new MyReceiver();
        registerReceiver(myReceiver, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            unregisterReceiver(mMyBroadcastReceiver);
            unregisterReceiver(myReceiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 初始化底边栏
     */
    private void initBottomBar() {
        findViewById(R.id.lay_main_pager).setOnClickListener(this);
        findViewById(R.id.lay_my_patient).setOnClickListener(this);
        findViewById(R.id.lay_personal_center).setOnClickListener(this);
        findViewById(R.id.lay_personal_centerfour).setOnClickListener(this);
//        findViewById(R.id.img_delete).setOnClickListener(this);
//        findViewById(R.id.btn_detail).setOnClickListener(this);


        ImageView mIvMainPager = (ImageView) findViewById(R.id.iv_main_pager);
        ImageView mIvmy_patient = (ImageView) findViewById(R.id.iv_my_patient);
        ImageView mIvPersonalCenter = (ImageView) findViewById(R.id.iv_personal_center);
        ImageView mIvPersonalCenterfour = (ImageView) findViewById(R.id.iv_personal_centerfour);
        images = new ImageView[]{mIvMainPager, mIvmy_patient, mIvPersonalCenter, mIvPersonalCenterfour};

        TextView mTvMainPager = (TextView) findViewById(R.id.tv_main_pager);
        TextView mTvMyPatient = (TextView) findViewById(R.id.tv_my_patient);
        TextView MtvPersonalCenter = (TextView) findViewById(R.id.tv_personal_center);
        TextView MtvPersonalCenterfour = (TextView) findViewById(R.id.tv_personal_centerfour);
        textViews = new TextView[]{mTvMainPager, mTvMyPatient, MtvPersonalCenter, MtvPersonalCenterfour};
    }

    /**
     * 初始化标题栏
     */
    private void initTopBar() {

        // 设置标题
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvTitle.setText(names[0]);
        // 隐藏右侧按钮
        mBtnBack = (ImageView) findViewById(R.id.btn_back);
        mBtnBack.setVisibility(View.GONE);
        //設置搜索按鈕
        mImgSearch = (ImageView) findViewById(R.id.img_search);
        mImgSearch.setBackgroundResource(R.drawable.icon_search);
        mImgSearch.setOnClickListener(this);
        //設置扫一扫按鈕
        mImgScan = (ImageView) findViewById(R.id.img_title);
        mImgScan.setVisibility(View.VISIBLE);
        mImgScan.setBackgroundResource(R.drawable.icon_new_message);
        mImgScan.setOnClickListener(this);

//        mRelActivity = (RelativeLayout) findViewById(R.id.rel_activity);
//        mRelActivity.setOnClickListener(this);
    }


    //设置状态选择效果
    private void seleted(int i) {
        for (int j = 0; j < images.length; j++) {
            if (j == i) {
                images[j].setBackgroundResource(press[j]);
                textViews[j].setTextColor(Color.parseColor("#feb333"));
                mTvTitle.setText(names[j]);
                this.tabHost.setCurrentTab(j);
            } else {
                images[j].setBackgroundResource(normal[j]);
                textViews[j].setTextColor(Color.parseColor("#777777"));
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.lay_main_pager:
                seleted(0);
                mImgSearch.setVisibility(View.GONE);
                mImgScan.setVisibility(View.VISIBLE);
                mImgScan.setBackgroundResource(R.drawable.icon_new_message);
                break;
            case R.id.lay_my_patient:
                mImgSearch.setVisibility(View.VISIBLE);
                mImgScan.setVisibility(View.VISIBLE);
                mImgScan.setBackgroundResource(R.drawable.icon_scan);
                seleted(1);
                break;
            case R.id.lay_personal_center:
                seleted(2);
                mImgSearch.setVisibility(View.GONE);
                mImgScan.setVisibility(View.GONE);
                break;
            case R.id.lay_personal_centerfour:
                seleted(3);
                mImgSearch.setVisibility(View.GONE);
                mImgScan.setVisibility(View.GONE);
                break;
            case R.id.img_title:
                if (tabHost.getCurrentTab() == 0) {
                    Intent intent = new Intent(this, MessageActivity.class);
                    startActivity(intent);
                } else if (tabHost.getCurrentTab() == 1) {
                    Intent intent5 = new Intent(this, CaptureActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("key", "setup");
                    intent5.putExtras(bundle);
                    intent5.putExtra("from", "0");
                    startActivity(intent5);
                }
//                mRelActivity.setVisibility(View.VISIBLE);
                break;

            case R.id.rel_activity:
                break;
            case R.id.img_search:
                Intent intent1 = new Intent(this, SearchDoctorActivity.class);
                startActivity(intent1);
                break;
        }
    }

    private class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConstantValue.Main_CHANGE)) {
                String position = intent.getStringExtra("position");
                tabHost.setCurrentTab(Integer.parseInt(position));
                seleted(Integer.parseInt(position));
            }
        }
    }

    public class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            mImgSearch.setVisibility(View.VISIBLE);
            mImgScan.setVisibility(View.VISIBLE);
            mImgScan.setBackgroundResource(R.drawable.icon_scan);
            seleted(1);
        }
    }


    /**
     * ***************************************** 登录 **************************************
     */

    private void login() {
//        DialogMaker.showProgressDialog(this, null, getString(R.string.logining), true, new DialogInterface.OnCancelListener() {
//            @Override
//            public void onCancel(DialogInterface dialog) {
//                if (loginRequest != null) {
//                    loginRequest.abort();
//                    onLoginDone();
//                }
//            }
//        }).setCanceledOnTouchOutside(false);

        // 云信只提供消息通道，并不包含用户资料逻辑。开发者需要在管理后台或通过服务器接口将用户帐号和token同步到云信服务器。
        // 在这里直接使用同步到云信服务器的帐号和token登录。
        // 这里为了简便起见，demo就直接使用了密码的md5作为token。
        // 如果开发者直接使用这个demo，只更改appkey，然后就登入自己的账户体系的话，需要传入同步到云信服务器的token，而不是用户密码。
        final String account = Token.getAccId();
        final String token = Token.getAccPwd();
//        final String account = "1232123";
//        final String token = "1232123";
        // 登录
        loginRequest = NIMClient.getService(AuthService.class).login(new LoginInfo(account, token));
        loginRequest.setCallback(new RequestCallback<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo param) {
                com.netease.nim.uikit.common.util.log.LogUtil.i(TAG, "login success");

                onLoginDone();
                DemoCache.setAccount(account);
                saveLoginInfo(account, token);

            }

            @Override
            public void onFailed(int code) {
                onLoginDone();
                if (code == 302 || code == 404) {
                    Toast.makeText(MainActivity.this, "帐号或密码错误", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainActivity.this, "登录失败: " + code, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onException(Throwable exception) {
                onLoginDone();
            }
        });

//        NIMClient.getService(SystemMessageObserver.class)
//                .observeUnreadCountChange(sysMsgUnreadCountChangedObserver, register);


    }

//    private Observer<Integer> sysMsgUnreadCountChangedObserver = new Observer<Integer>() {
//        @Override
//        public void onEvent(Integer unreadCount) {
//
//        }
//    };

    private void onLoginDone() {
        loginRequest = null;
        DialogMaker.dismissProgressDialog();
    }

    private void saveLoginInfo(final String account, final String token) {
        SharedPreferencesUtils.setParam(MainActivity.this, "WYYaccountpatient", account);
        SharedPreferencesUtils.setParam(MainActivity.this, "WYYtokenpatient", token);
    }

    //DEMO中使用 username 作为 NIM 的account ，md5(password) 作为 token
    //开发者需要根据自己的实际情况配置自身用户系统和 NIM 用户系统的关系
    private String tokenFromPassword(String password) {
        String appKey = readAppKey(this);
        boolean isDemo = "45c6af3c98409b18a84451215d0bdd6e".equals(appKey)
                || "fe416640c8e8a72734219e1847ad2547".equals(appKey);

        return isDemo ? com.netease.nim.uikit.common.util.string.MD5.getStringMD5(password) : password;
    }

    private static String readAppKey(Context context) {
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (appInfo != null) {
                return appInfo.metaData.getString("com.netease.nim.appKey");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
